<template>
  <div>
    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="filter-form">
        <div class="filter-row">
          <div class="filter-item">
            <label>状态：</label>
            <select v-model="filters.status">
              <option value="">全部</option>
              <option value="1">启用</option>
              <option value="0">禁用</option>
            </select>
          </div>
          
          <div class="filter-item">
            <label>用户名称：</label>
            <input 
              type="text" 
              v-model="filters.username" 
              placeholder="请输入用户名称"
            />
          </div>
          
          <div class="filter-item">
            <label>用户昵称：</label>
            <input 
              type="text" 
              v-model="filters.truename" 
              placeholder="请输入用户昵称"
            />
          </div>
        </div>
        
        <div class="filter-row">
          <div class="filter-item">
            <label>手机号：</label>
            <input 
              type="text" 
              v-model="filters.phone" 
              placeholder="请输入手机号"
            />
          </div>
          
          <div class="filter-item">
            <label>微信昵称：</label>
            <input 
              type="text" 
              v-model="filters.nickname" 
              placeholder="请输入微信昵称"
            />
          </div>
          
          <div class="filter-item">
            <button @click="handleSearch" class="search-btn">查询</button>
            <button @click="handleReset" class="reset-btn">重置</button>
          </div>
        </div>
      </div>
    </div>

    <div class="customer-management">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading">加载中...</div>
      
      <!-- 客户列表 -->
      <div class="customer-list" v-else>
        <div class="table-container">
          <table class="customer-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>头像</th>
                <th>微信昵称</th>
                <th>手机号</th>
                <th>用户名称</th>
                <th>平台角色</th>
                <th>客户昵称</th>
                <th>性别</th>
                <th>创建时间</th>
                <th>备注</th>
                <th>状态</th>
                <th>操作</th>

              </tr>
            </thead>
            <tbody>
              <tr v-for="customer in customers" :key="customer.id">
                <td>{{ customer.id }}</td>
                <td>
                  <img 
                    v-if="customer.headimg" 
                    :src="customer.headimg" 
                    alt="头像" 
                    class="avatar"
                  />
                  <span v-else class="no-avatar">无头像</span>
                </td>
                <td>{{ customer.nickname }}</td>
                <td>{{ customer.phone }}</td>
                <td>{{ customer.username }}</td>
                <td>{{ customer.role }}</td>
                <td>{{ customer.truename }}</td>
                <td>{{ formatSex(customer.sex) }}</td>
                <td>{{ formatDate(customer.create_at) }}</td>
                <td class="desc-cell">{{ customer.desc || '无' }}</td>
                <td>
                  <span 
                    :class="['status', customer.status === 1 ? 'active' : 'inactive']"
                  >
                    {{ customer.status === 1 ? '启用' : '禁用' }}
                  </span>
                </td>
                <td>
                  <button @click="handlePassword(customer)" class="edit-btn">重置密码</button>
                </td>

              </tr>
            </tbody>
          </table>
          
          <!-- 空状态 -->
          <div v-if="customers.length === 0" class="empty-state">
            暂无客户数据
          </div>
        </div>
        
        <!-- 分页 -->
        <div class="pagination" v-if="total > 0">
          <button 
            @click="prevPage" 
            :disabled="currentPage === 1"
            class="page-btn"
          >
            上一页
          </button>
          
          <span class="page-info">
            第 {{ currentPage }} 页 / 共 {{ totalPages }} 页 (共 {{ total }} 条记录)
          </span>
          
          <button 
            @click="nextPage" 
            :disabled="currentPage === totalPages"
            class="page-btn"
          >
            下一页
          </button>
          
          <div class="page-size">
            <label>每页显示：</label>
            <select v-model="pageSize" @change="handlePageSizeChange">
              <option value="10">10</option>
              <option value="20">20</option>
              <option value="50">50</option>
            </select>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { getList } from '@/api/customer';
import { ElMessage, ElMessageBox } from 'element-plus'
import { systemUserApi } from '@/api/user'

// 定义客户数据类型
interface Customer {
  id: number
  openid: string
  headimg: string
  nickname: string
  phone: string
  username: string
  password: string
  role: string
  truename: string
  sex: number
  create_at: string
  desc: string
  status: number
}

// 定义筛选条件类型
interface FilterConditions {
  status: string
  username: string
  truename: string
  phone: string
  nickname: string
}

// 响应式数据
const customers = ref<Customer[]>([])
const filters = ref<FilterConditions>({
  status: '',
  username: '',
  truename: '',
  phone: '',
  nickname: ''
})
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)


// 计算属性 - 总页数
const totalPages = computed(() => {
  return Math.ceil(total.value / pageSize.value)
})

// 方法 - 获取客户列表
const fetchCustomers = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
        page: currentPage.value,
        page_size: pageSize.value,
        tenant: currentTenant.value, // 添加租户参数
        ...filters.value
    }
    
    const result = await getList(params)
    console.log(result)
    
    if (result.code === 200) {
      customers.value = result.data.list
      total.value = result.data.total
      currentPage.value = result.data.current_page
      pageSize.value = result.data.page_size
    } else {
      console.error('获取客户列表失败:', result.message)
      customers.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('API调用错误:', error)
    customers.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 方法 - 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchCustomers()
}

// 方法 - 重置筛选条件
const handleReset = () => {
  filters.value = {
    status: '',
    username: '',
    truename: '',
    phone: '',
    nickname: ''
  }
  currentPage.value = 1
  fetchCustomers()
}

// 方法 - 上一页
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
    fetchCustomers()
  }
}

// 方法 - 下一页
const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    fetchCustomers()
  }
}

// 方法 - 每页显示数量变化
const handlePageSizeChange = () => {
  currentPage.value = 1
  fetchCustomers()
}

// 方法 - 格式化性别
const formatSex = (sex: number): string => {
  const sexMap: { [key: number]: string } = {
    0: '未知',
    1: '男',
    2: '女'
  }
  return sexMap[sex] || '未知'
}

// 方法 - 格式化日期
const formatDate = (dateStr: string): string => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleDateString()
}

// 添加用于存储当前租户的响应式变量
const currentTenant = ref<string | null>(localStorage.getItem('currentTenant'))

// 添加监听 localStorage 中 currentTenant 变化的逻辑
const watchStorage = () => {
  const originalSetItem = localStorage.setItem
  const originalRemoveItem = localStorage.removeItem
  
  localStorage.setItem = function(key, value) {
    if (key === 'currentTenant') {
      currentTenant.value = value
    }
    originalSetItem.apply(this, [key, value])
  }
  
  localStorage.removeItem = function(key) {
    if (key === 'currentTenant') {
      currentTenant.value = null
    }
    originalRemoveItem.apply(this, [key])
  }
}

// 监听 currentTenant 变化并重新获取数据
watch(currentTenant, (newTenant, oldTenant) => {
  if (newTenant !== oldTenant) {
    // 重置分页到第一页
    currentPage.value = 1
    // 获取新租户下的客户数据
    fetchCustomers()
  }
})

const handlePassword = (row: any) => {
  ElMessageBox.confirm(
    `确定要重置用户 "${row.truename}" 的密码吗？`,
    '重置密码确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      // 准备重置密码的数据，用户名+123
      const resetData = {
        id: row.id,
        password: row.username + '123'
      };
      
      // 调用重置密码API
      const result = await systemUserApi.resetPassword2(resetData);
      
      if (result.code === 200) {
        fetchCustomers()
        ElMessage.success('密码重置成功');
      } else {
        ElMessage.error('密码重置失败: ' + result.message);
      }
    } catch (error: any) {
      ElMessage.error('密码重置失败: ' + (error.message || '未知错误'));
    }
  }).catch(() => {
    // 用户取消操作
    ElMessage.info('已取消重置密码');
  });
}

// 生命周期 - 组件挂载
onMounted(() => {
  watchStorage()
  fetchCustomers()
})
</script>

<style scoped>
.customer-management {
  padding: 20px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  color: #333;
}

.filter-section {
  background-color: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.filter-section h2 {
  margin-top: 0;
  color: #2c3e50;
  border-bottom: 1px solid #eaeaea;
  padding-bottom: 10px;
}

.filter-form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.filter-row {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.filter-item label {
  font-weight: 500;
  min-width: 80px;
}

.filter-item input,
.filter-item select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 12px;
  min-width: 180px;
}

.search-btn,
.reset-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.2s;
}

.search-btn {
  background-color: #409eff;
  color: white;
}

.search-btn:hover {
  background-color: #79bbff;
}

.reset-btn {
  background-color: #95a5a6;
  color: white;
  margin-left: 10px;
}

.reset-btn:hover {
  background-color: #7f8c8d;
}

.loading {
  text-align: center;
  padding: 40px;
  color: #409eff;
  font-size: 14px;
}

.customer-list h2 {
  color: #2c3e50;
  margin-bottom: 15px;
}

.table-container {
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.customer-table {
  width: 100%;
  font-size: 14px;
  border-collapse: collapse;
}

.customer-table th,
.customer-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #eaeaea;
}

.customer-table th {
  background-color: #f1f5f9;
  font-weight: 600;
  color: #2c3e50;
}

.customer-table tr:hover {
  background-color: #f8f9fa;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.no-avatar {
  color: #95a5a6;
  font-style: italic;
}

.desc-cell {
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 10px;
  font-weight: 500;
}

.status.active {
  background-color: #d4edda;
  color: #155724;
}

.status.inactive {
  background-color: #f8d7da;
  color: #721c24;
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #95a5a6;
  font-style: italic;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  gap: 15px;
  flex-wrap: wrap;
}

.page-btn {
  padding: 8px 16px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.page-btn:hover:not(:disabled) {
  background-color: #79bbff;
}

.page-btn:disabled {
  background-color: #bdc3c7;
  cursor: not-allowed;
}

.page-info {
  font-weight: 500;
}

.page-size {
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-size select {
  padding: 6px 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

@media (max-width: 768px) {
  .filter-row {
    flex-direction: column;
    gap: 10px;
  }
  
  .filter-item {
    width: 100%;
  }
  
  .filter-item input,
  .filter-item select {
    flex: 1;
  }
  
  .customer-table {
    font-size: 12px;
  }
  
  .customer-table th,
  .customer-table td {
    padding: 8px 10px;
  }
  
  .pagination {
    flex-direction: column;
    gap: 10px;
  }
}
</style>